package org.iabako.client.tools;

import com.google.gwt.event.dom.client.*;
import com.google.gwt.event.logical.shared.SelectionEvent;
import com.google.gwt.event.logical.shared.SelectionHandler;
import com.google.gwt.user.client.ui.SuggestOracle;
import org.iabako.client.ui.layout.field.InputTextSuggest;
import org.iabako.shared.entity.business.AbstractEntity;
import org.iabako.shared.iservice.generic.SuggestServiceAsync;
import org.iabako.shared.tools.GenericTools;

/**
 * Created by jose on 19/08/14.
 */
public class DefaultSuggestSelectionHandler implements SelectionHandler<SuggestOracle.Suggestion>, KeyUpHandler, BlurHandler {

    protected SuggestServiceAsync suggestServiceAsync;
    protected InputTextSuggest inputTextSuggest;
    protected AbstractEntity entity;

    public DefaultSuggestSelectionHandler(SuggestServiceAsync suggestServiceAsync, InputTextSuggest inputTextSuggest) {
        this.suggestServiceAsync = suggestServiceAsync;
        this.inputTextSuggest = inputTextSuggest;
    }

    public void onBlur(BlurEvent event) {
        if (GenericTools.isEmpty(inputTextSuggest.getHiddenSelectionCode().getValue())) {
            inputTextSuggest.enableNoValueString();
            entity = null;
        }
        customOnBlur();
    }

    public void onKeyUp(KeyUpEvent event) {
        if (event.getNativeEvent().getKeyCode() == KeyCodes.KEY_ENTER
                && GenericTools.isEmpty(inputTextSuggest.getHiddenSelectionCode().getValue())) {
            event.getNativeEvent().stopPropagation();
            inputTextSuggest.getInputField().setValue("");
        }
    }

    public void onSelection(SelectionEvent<SuggestOracle.Suggestion> event) {
        String hiddenSelectionCode = inputTextSuggest.getHiddenSelectionCode().getValue();
        if (!GenericTools.isEmpty(hiddenSelectionCode)) {
            suggestServiceAsync.getByHiddenSelectionCode(hiddenSelectionCode, new IabakoAsyncCallback<AbstractEntity>() {
                public void onSuccess(AbstractEntity result) {
                    entity = result;
                    customOnSuccessSelection();
                    super.onSuccess(result);
                }
            });
        }
    }

    public AbstractEntity getEntity() {
        return entity;
    }

    protected void customOnSuccessSelection() {
        //to be override
    }

    protected void customOnBlur() {
        //to be override
    }

    public void cleanValue() {
        entity = null;
        inputTextSuggest.setValue(null);
    }

    public void setEntity(AbstractEntity entity) {
        this.entity = entity;
    }

    public void setText(String text) {
        inputTextSuggest.setValue(text);
    }

    public void setHiddenSelectionCode(String hiddenSelectionCode) {
        inputTextSuggest.getHiddenSelectionCode().setText(hiddenSelectionCode);
    }
}
